package com.yjd.msg.comm.mns;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class LimitedLongPolling {
    private static Logger logger = Logger.getLogger(LimitedLongPolling.class);

    protected static MNSClient sMNSClient;

    public static void WorkerFunc(int workerId,String queueName)
    {
        MessageReceiver receiver = new MessageReceiver(workerId+"", sMNSClient, queueName);
        while (true) {
            Message message = receiver.receiveMessage();
            logger.info("Thread" + workerId + " GOT ONE MESSAGE! " + message.getMessageId());
            sMNSClient.getQueueRef("TestQueue").deleteMessage(message.getReceiptHandle());
        }
    }

    public static void main(String args[]) {
        CloudAccount account = new CloudAccount("ACCESS_ID", "ACCESS_KEY", "ENDPOINT");
        sMNSClient = account.getMNSClient();
        sMNSClient.getQueueRef("TestQueue").delete();
        sMNSClient.getQueueRef("TestQueue").create();

        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                WorkerFunc(1,"q");
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                WorkerFunc(2,"q");
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                WorkerFunc(3,"q");
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Message message = new Message("OneMessage");
        List<Message> messages = new ArrayList<Message>();
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        messages.add(message);
        sMNSClient.getQueueRef("TestQueue").batchPutMessage(messages);

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // keep looping util the end of world
        try {
            thread1.join();
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
